<template>
  <div class="crud-container">
    <!-- 工具栏 -->
    <n-card v-if="showToolbar" class="toolbar-card" :bordered="false">
      <div class="toolbar">
        <div class="left">
          <n-space>
            <!-- 批量操作按钮 -->
            <template v-if="config.tableConfig?.batchActions && checkedRowKeys.length">
              <n-button v-for="action in BATCH_ACTIONS" :key="action.action" :type="action.type"
                @click="handleBatchAction(action.action)" class="custom-button">
                <template #icon>
                  <n-icon>
                    <component :is="action.icon" />
                  </n-icon>
                </template>
                <span class="button-label">{{ action.label }}</span>
              </n-button>
            </template>
          </n-space>
        </div>
        <div class="right">
          <n-space>
            <!-- 刷新按钮 -->
            <n-button v-if="config.toolbar?.refresh" quaternary circle @click="handleRefresh">
              <template #icon><n-icon><reload-outlined /></n-icon></template>
            </n-button>

            <!-- 密度调整 -->
            <n-popselect v-if="config.toolbar?.density" v-model:value="tableSize" :options="TABLE_SIZES">
              <n-button quaternary circle>
                <template #icon><n-icon><column-height-outlined /></n-icon></template>
              </n-button>
            </n-popselect>

            <!-- 列设置 -->
            <n-popselect v-if="config.toolbar?.setting" v-model:value="visibleColumns" :options="columnOptions"
              multiple>
              <n-button quaternary circle>
                <template #icon><n-icon><setting-outlined /></n-icon></template>
              </n-button>
            </n-popselect>

            <!-- 全屏按钮 -->
            <n-button v-if="config.toolbar?.fullscreen" quaternary circle @click="toggleFullscreen">
              <template #icon>
                <n-icon>
                  <component :is="isFullscreen ? 'fullscreen-exit-outlined' : 'fullscreen-outlined'" />
                </n-icon>
              </template>
            </n-button>
          </n-space>
        </div>
      </div>
    </n-card>

    <!-- 查询区域 -->
    <n-card v-if="config.searchable" class="search-card" :bordered="false">
      <template #header>
        <div class="search-header">
          <span class="card-label">{{ config.title }}</span>
          <n-button text @click="toggleSearchArea">
            {{ showSearchArea ? "收起" : "展开" }}
            <template #icon>
              <n-icon size="14">
                <down-outlined v-if="!showSearchArea" />
                <up-outlined v-if="showSearchArea" />
              </n-icon>
            </template>
          </n-button>
        </div>
      </template>
      <div class="search-content" :class="{ 'search-content-collapsed': !showSearchArea }">
        <n-grid :cols="24" :x-gap="12" :y-gap="4">
          <n-grid-item v-for="field in searchFields" :key="field.key" :span="4">
            <n-form-item :label="field.label" label-placement="left">
              <!-- 输入框 -->
              <n-input v-if="field.type === 'input'" v-model:value="searchForm[field.key]"
                :placeholder="field.placeholder || '请输入'" />

              <!-- 选择器 -->
              <n-select v-else-if="field.type === 'select'" v-model:value="searchForm[field.key]"
                :options="field.options" :placeholder="field.placeholder || '请选择'" />

              <!-- 日期选择器 -->
              <n-date-picker v-else-if="field.type === 'date'" v-model:value="searchForm[field.key]" type="datetime"
                :placeholder="field.placeholder || '请选择'" />
            </n-form-item>
          </n-grid-item>
        </n-grid>
        <div class="search-actions">
          <n-space>
            <n-button @click="resetSearch">重置</n-button>
            <n-button type="primary" @click="handleSearch">查询</n-button>
          </n-space>
        </div>
      </div>
    </n-card>

    <!-- 表格区域 -->
    <n-card class="table-card" title=" ">
      <template #header-extra>
        <slot name="table-header-left"></slot>
        <n-space>
          <slot name="table-header-right"></slot>
          <n-button v-if="config.creatable" type="primary" @click="handleAdd">
            <template #icon>
              <n-icon><plus-outlined /></n-icon>
            </template>
            新增
          </n-button>
        </n-space>
      </template>

      <div class="table-container">
        <el-table
          :data="tableData"
          :border="false"
          style="width: 100%"
          :row-key="(row) => row[config.primaryKey]"
          :tree-props="{
            children: config.tableConfig?.childrenKey || 'children',
            hasChildren: 'hasChildren'
          }"
          :default-expand-all="config.tableConfig?.defaultExpandAll"
          v-loading="loading"
          :class="{ 'custom-table': true }"
        >
          <!-- 序号列 -->
          <el-table-column
            type="index"
            label="序号"
            width="80"
            align="center"
          />

          <!-- 动态生成列 -->
          <template v-for="col in columns" :key="col.key">
            <el-table-column
              :prop="col.key"
              :label="col.title"
              :width="col.width"
              :fixed="col.fixed"
              :sortable="col.sortable"
              :align="col.align"
              show-overflow-tooltip
            >
              <template #default="scope">
                <!-- 自定义渲染列 -->
                <template v-if="col.render">
                  <component 
                    :is="renderCustomColumn(col.render, scope.row)"
                    v-if="isVueComponent(col.render, scope.row)"
                  />
                  <span v-else>{{ renderCustomColumn(col.render, scope.row) }}</span>
                </template>
                <!-- 日期时间格式化 -->
                <template v-else-if="col.type === 'datetime'">
                  {{ formatDateTime(scope.row[col.key]) }}
                </template>
                <!-- 默认渲染 -->
                <template v-else>
                  {{ scope.row[col.key] }}
                </template>
              </template>
            </el-table-column>
          </template>

          <!-- 操作列 -->
          <el-table-column
            v-if="config.actionable !== false"
            label="操作"
            :width="calculateActionWidth(config)"
            fixed="right"
            align="center"
          >
            <template #default="scope">
              <div class="action-buttons">
                <!-- 自定义操作按钮 -->
                <template v-if="config.customActions">
                  <el-button
                    v-for="action in config.customActions"
                    :key="action.label"
                    v-show="!action.show || action.show(scope.row)"
                    :type="action.type || 'primary'"
                    link
                    @click="action.onClick(scope.row)"
                  >
                    <el-icon v-if="action.icon">
                      <component :is="action.icon" />
                    </el-icon>
                    {{ action.label }}
                  </el-button>
                </template>

                <!-- 默认操作按钮 -->
                <el-button
                  v-if="config.editable"
                  type="primary"
                  link
                  @click="handleEdit(scope.row)"
                >
                  <el-icon><edit /></el-icon>
                  编辑
                </el-button>

                <el-popconfirm
                  v-if="config.deletable"
                  title="确认删除该记录吗？"
                  @confirm="handleDelete(scope.row)"
                >
                  <template #reference>
                    <el-button type="danger" link>
                      <el-icon><delete /></el-icon>
                      删除
                    </el-button>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div v-if="config.tableConfig.pagination" class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </n-card>
    <!-- 表单弹窗 -->
    <n-modal v-model:show="showModal" :mask-closable="false" preset="card"
      :style="{ width: config.formConfig?.width || '600px' }" :title="isEdit ? '编辑' : '新增'" size="huge"
      :bordered="false">
      <n-form ref="formRef" :model="formData" :rules="config.rules"
        :label-placement="config.formConfig?.labelPlacement || 'left'"
        :label-width="config.formConfig?.labelWidth || 100" :size="config.formConfig?.size || 'medium'"
        require-mark-placement="right-hanging">
        <n-grid :cols="config.formConfig?.gridSpan || 24" :x-gap="12">
          <n-grid-item v-for="field in formFields" :key="field.key" :span="field.span || 24"
            v-show="!field.show || field.show(formData)">
            <n-form-item :label="field.label" :path="field.key">
              <!-- 自定义渲染 -->
              <template v-if="field.type === 'custom'">
                <component :disabled="isEdit ? field.update_disabled : field.add_disabled" :is="field.render"
                  :value="formData[field.key]" @update:value="(val) => formData[field.key] = val" />
              </template>
              <!-- 输入框 -->
              <n-input :disabled="isEdit ? field.update_disabled : field.add_disabled"
                v-if="['input', 'password'].includes(field.type)" v-model:value="formData[field.key]" :type="field.type"
                show-password-on="click" :placeholder="field.placeholder || '请输入'" clearable />

              <!-- 文本域 -->
              <n-input :disabled="isEdit ? field.update_disabled : field.add_disabled"
                v-else-if="field.type === 'textarea'" v-model:value="formData[field.key]" type="textarea"
                :placeholder="field.placeholder || '请输入'" :autosize="{ minRows: 3, maxRows: 5 }" clearable />

              <!-- 选择器 -->
              <n-select :disabled="isEdit ? field.update_disabled : field.add_disabled"
                v-else-if="field.type === 'select'" v-model:value="formData[field.key]" :options="field.options"
                :placeholder="field.placeholder || '请选择'" clearable />

              <!-- 日期选择器 -->
              <n-date-picker :disabled="isEdit ? field.update_disabled : field.add_disabled"
                v-else-if="field.type === 'date'" v-model:value="formData[field.key]" type="datetime"
                :placeholder="field.placeholder || '请选择'" clearable />

              <!-- 级联选择器 -->
              <n-cascader v-else-if="field.type === 'cascader'"
                :value="formData[field.key]"
                :options="field.options"
                :placeholder="field.placeholder || '请选择'"
                :disabled="isEdit ? field.update_disabled : field.add_disabled"
                :clearable="field.clearable"
                :filterable="field.filterable"
                @update:value="(value) => formData[field.key] = value"
                :style="{ width: '100%' }"
              />

              <!-- TreeSelect -->
              <n-tree-select v-else-if="field.type === 'tree-select'"
                :value="formData[field.key]"
                :options="field.options"
                :placeholder="field.placeholder || '请选择'"
                :disabled="isEdit ? field.update_disabled : field.add_disabled"
                :clearable="field.clearable"
                :filterable="field.filterable"
                :default-expand-all="field.defaultExpandAll"
                :check-strategy="field.checkStrategy"
                :key-field="field.keyField"
                :label-field="field.labelField"
                :children-field="field.childrenField"
                :remote="field.remote"
                :cascade="field.cascade"
                :multiple="field.multiple"
                :virtual-scroll="field.virtualScroll"
                :max-height="field.maxHeight"
                @update:value="(value) => formData[field.key] = value"
                :style="{ width: '100%' }"
              />
            </n-form-item>
          </n-grid-item>
        </n-grid>
      </n-form>

      <template #footer>
        <n-space justify="end">
          <n-button v-if="config.formConfig?.showReset" @click="handleReset">
            {{ config.formConfig?.resetText || '重置' }}
          </n-button>
          <n-button @click="closeModal">取消</n-button>
          <n-button type="primary" :loading="submitting" @click="handleSubmit">
            {{ config.formConfig?.submitText || '确定' }}
          </n-button>
        </n-space>
      </template>
    </n-modal>

    <!-- 排序弹窗 -->
    <n-modal v-model:show="showSortModal" title="岗位排序" preset="dialog">
      <n-tree
        block-line
        draggable
        :data="sortTreeData"
        :default-expanded-keys="expandedRowKeys"
        style="max-height: 400px; overflow: auto;"
      />
      <template #footer>
        <n-space justify="end">
          <n-button @click="showSortModal = false">取消</n-button>
          <n-button type="primary" @click="handleSortConfirm">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, computed, h, watch, onMounted, onBeforeUnmount, nextTick } from "vue";
import {
  NButton,
  NCard,
  NDataTable,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NSpace,
  NModal,
  NIcon,
  NPopconfirm,
  NDatePicker,
  NGrid,
  NGridItem,
  NSwitch,
  NPopselect,
  useDialog,
  NCascader,
  NTreeSelect,
  NTree,
} from "naive-ui";
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  DownOutlined,
  UpOutlined,
  ReloadOutlined,
  ColumnHeightOutlined,
  SettingOutlined,
  FullscreenOutlined,
  FullscreenExitOutlined,
} from "@vicons/antd";
import { DEFAULT_CRUD_CONFIG, TABLE_SIZES, BATCH_ACTIONS } from '@/constants/crud'
import { debounce } from 'lodash-es'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Edit,
  Delete
} from '@element-plus/icons-vue'

const props = defineProps({
  // 配置对象
  config: {
    type: Object,
    required: true,
    default: () => ({
      // 基础配置
      title: '',
      apiPrefix: '',
      primaryKey: 'id',
      searchable: true,
      creatable: true,
      editable: true,
      deletable: true,
      switchable: false,
      switchKey: 'status',

      // 表格配置
      tableConfig: {
        rowKey: undefined,
        pagination: true,
        bordered: false,
        striped: true,
        childrenKey: 'children',
        indent: 16,
        size: 'medium',
        scrollX: 1400,
        defaultExpandAll: true
      },

      // 工具栏配置
      toolbar: {
        refresh: true,
        density: true,
        setting: true,
        fullscreen: true
      },

      // 搜索配置
      searchConfig: {
        autoSearch: true,
        debounceTime: 300
      },

      // 表单配置
      formConfig: {
        width: '600px',
        labelPlacement: 'left',
        labelWidth: 100,
        gridSpan: 24,
        showReset: true,
        resetText: '重置',
        submitText: '确定'
      },

      // 空数组/对象配置
      columns: [],
      searchFields: [],
      formFields: [],
      rules: {},

      // 子项配置
      childConfig: {
        apiPrefix: '', // 子项接口前缀
        parentField: 'parent_id', // 父级关联字段名
        inheritFields: [], // 需要从父级继承的字段
        useParentForm: true, // 使用父级的表单配置
        extraFields: [], // 子项额外的表单字段
        excludeFields: [], // 需要从父级表单中排除的字段
      }
    }),
  },
  // 数据源
  data: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(["update", "delete", "create", "switch-change"]);
const dialog = useDialog();

// 状态管理
const loading = ref(false);
const submitting = ref(false);
const showModal = ref(false);
const isEdit = ref(false);
const searchText = ref("");
const formRef = ref(null);
const formData = ref({});
const tableData = ref(props.data);

// 表格数据相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 分页配置
const pagination = computed(() => ({
  page: currentPage.value,
  pageSize: pageSize.value,
  total: total.value,
  onChange: handlePageChange,
  onUpdatePageSize: (size) => {
    pageSize.value = size;
    fetchData();
  }
}));

// 查询相关
const showSearchArea = ref(false);
const searchForm = ref({});
const searchFields = computed(() => props.config.searchFields || []);

// 新增的状态和计算属性
const checkedRowKeys = ref([])
const tableSize = ref(DEFAULT_CRUD_CONFIG.tableConfig.size)
const isFullscreen = ref(false)
const visibleColumns = ref([])

// 添加展开行的状态控制
const expandedRowKeys = ref([])

// 获取所有可展开的行的key
const getAllExpandableKeys = (data) => {
  const keys = []
  const getKeys = (items) => {
    if (!Array.isArray(items)) return
    items.forEach(item => {
      if (item[props.config.primaryKey]) {
        keys.push(item[props.config.primaryKey])
      }
      if (Array.isArray(item.children) && item.children.length > 0) {
        getKeys(item.children)
      }
    })
  }
  getKeys(data)
  return keys
}

// 监听数据变化，更新展开状态
watch(() => tableData.value, (newData) => {
  if (props.config.tableConfig?.defaultExpandAll && Array.isArray(newData)) {
    expandedRowKeys.value = getAllExpandableKeys(newData)
  }
}, { immediate: true })

// 显示工具栏
const showToolbar = computed(() => {
  const { toolbar = {} } = props.config
  return Object.values(toolbar).some(v => v)
})

// 列选项
const columnOptions = computed(() => {
  return props.config.columns.map(col => ({
    label: col.title,
    value: col.key
  }))
})

// 计算操作列宽度
const calculateActionWidth = (config) => {
  let width = 0
  const buttonPadding = 24 // 按钮左右内边距总和
  const buttonMargin = 8 // 按钮间距
  const iconWidth = 16 // 图标宽度
  const textPadding = 4 // 文字和图标间距

  // 计算自定义按钮宽度
  if (config.customActions) {
    config.customActions.forEach(action => {
      // 文字宽度 (假设每个中文字符16px，英文字符8px)
      const textWidth = [...action.label].reduce((w, char) => {
        return w + (/[\u4e00-\u9fa5]/.test(char) ? 16 : 8)
      }, 0)
      
      // 单个按钮总宽度 = 文字宽度 + 内边距 + 图标(如果有) + 文字和图标间距(如果有图标)
      width += textWidth + buttonPadding + (action.icon ? (iconWidth + textPadding) : 0)
    })
  }

  // 计算默认按钮宽度
  if (config.editable) {
    width += 16 + buttonPadding + iconWidth + textPadding // "编辑"两个字
  }
  if (config.deletable) {
    width += 16 + buttonPadding + iconWidth + textPadding // "删除"两个字
  }

  // 添加按钮之间的间距
  const totalButtons = (config.customActions?.length || 0) + 
    (config.editable ? 1 : 0) + 
    (config.deletable ? 1 : 0)
  width += (totalButtons - 1) * buttonMargin

  // 添加一些额外的空间，确保有足够的余量
  width += 32

  return Math.max(width, 120) // 设置最小宽度
}

// 在生成操作列时使用
const actionColumn = computed(() => ({
  label: '操作',
  width: calculateActionWidth(props.config),
  fixed: 'right',
  align: 'center'
}))

// 修改生成操作列的方法
const generateActionColumn = () => {
  return {
    title: '操作',
    key: 'actions',
    width: 280,
    fixed: 'right',
    render: (row) => {
      const actions = []
      // 添加自定义操作按钮
      if (props.config.customActions) {
        props.config.customActions.forEach(action => {
          // 检查按钮是否应该显示,传入当前行和父行数据
          if (action.show && !action.show(row)) {
            return
          }

          actions.push(
            h(
              NButton,
              {
                size: "small",
                quaternary: true,
                type: action.type || "info",
                onClick: () => action.onClick(row),
              },
              {
                default: () => action.label,
                icon: () => action.icon ? h(action.icon) : null
              }
            )
          )
        })
      }

      // 添加默认的编辑和删除按钮
      if (props.config.editable) {
        actions.push(
          h(
            NButton,
            {
              size: "small",
              quaternary: true,
              type: "info",
              onClick: () => handleEdit(row),
            },
            { default: () => "编辑", icon: () => h(EditOutlined) }
          )
        )
      }

      if (props.config.deletable) {
        actions.push(
          h(
            NPopconfirm,
            {
              onPositiveClick: () => handleDelete(row),
            },
            {
              default: () => "确认删除该记录吗？",
              trigger: () =>
                h(
                  NButton,
                  {
                    size: "small",
                    quaternary: true,
                    type: "error",
                  },
                  { default: () => "删除", icon: () => h(DeleteOutlined) }
                ),
            }
          )
        )
      }

      return h('div', { 
        style: 'display: flex; gap: 3px; flex-wrap: nowrap; justify-content: flex-start;' 
      }, actions)
    }
  }
}

// 修改列配置的生成
const columns = computed(() => {
  // 直接返回处理后的列，不需要手动添加序号列
  return props.config.columns.map(col => {
    // 处理日期时间类型
    if (col.key === 'created_at' || col.key === 'updated_at' || col.type === 'datetime') {
      return {
        ...col,
        type: 'datetime'
      }
    }
    return col
  }).filter(col => {
    return !visibleColumns.value.length || visibleColumns.value.includes(col.key)
  })
})

// 切换查询区域显示状态
const toggleSearchArea = () => {
  showSearchArea.value = !showSearchArea.value;
};

// 修改树形排序方法
const buildTreeData = (data) => {
  // 构建id到节点的映射
  const idMap = new Map()
  data.forEach(item => {
    idMap.set(item[props.config.primaryKey], { 
      ...item,
      hasChildren: false // 初始化 hasChildren 属性
    })
  })
  
  // 构建树形结构
  const result = []
  data.forEach(item => {
    const node = idMap.get(item[props.config.primaryKey])
    const parentId = item[props.config.childConfig?.parentField || 'parent_id']
    
    if (!parentId) {
      result.push(node)
    } else if (idMap.has(parentId)) {
      const parent = idMap.get(parentId)
      if (!parent.children) {
        parent.children = []
      }
      parent.hasChildren = true // 设置父节点的 hasChildren 属性
      parent.children.push(node)
    }
  })

  // 递归排序
  const sortNodes = (nodes) => {
    if (!Array.isArray(nodes)) return
    nodes.sort((a, b) => (Number(a.sort) || 0) - (Number(b.sort) || 0))
    nodes.forEach(node => {
      if (node.children && node.children.length > 0) {
        sortNodes(node.children)
      }
    })
  }

  sortNodes(result)
  return result
}

// 修改 fetchData 方法
const fetchData = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm.value
    }

    const data = await request.get(`${props.config.apiPrefix}`, { params })
    console.log('Fetched Data:', data)

    if (props.config.tableConfig.pagination) {
      tableData.value = data.list
      total.value = data.pagination.total
    } else {
      // 直接使用数据，不需要额外处理
      tableData.value = Array.isArray(data) ? data : []
    }
  } catch (error) {
    console.error('Failed to fetch data:', error)
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1; // 重置到第一页
  fetchData(); // 重新获取数据
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm.value).forEach(key => {
    searchForm.value[key] = null;
  });
  handleSearch(); // 重新搜索
};

// 新增处理
const handleAdd = async () => {
  isEdit.value = false;
  showModal.value = true;
  formData.value = {};
};

// 编辑处理
const handleEdit = async (row) => {
  isEdit.value = true;
  showModal.value = true;
  formData.value = { ...row };
};

// 获取实际使用的API前缀
const getApiPrefix = (data) => {
  return props.config.childConfig?.apiPrefix && data?.[props.config.childConfig.parentField]
    ? props.config.childConfig.apiPrefix
    : props.config.apiPrefix
}

// 修改提交处理
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitting.value = true

    const apiPrefix = getApiPrefix(formData.value)

    if (isEdit.value) {
      await request.put(`${apiPrefix}/${formData.value[props.config.primaryKey]}`, formData.value)
      message.success('更新成功')
    } else {
      await request.post(apiPrefix, formData.value)
      message.success('创建成功')
    }

    showModal.value = false
    await fetchData()
  } finally {
    submitting.value = false
  }
}

// 修改删除处理
const handleDelete = async (row) => {
  const apiPrefix = getApiPrefix(row)
  await request.delete(`${apiPrefix}/${row[props.config.primaryKey]}`)
  message.success('删除成功')
  fetchData()
}

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchData();
};

// 关闭弹窗
const closeModal = () => {
  showModal.value = false;
  formData.value = {};
};

// 监听数据变化
watch(
  () => props.data,
  (newData) => {
    tableData.value = newData;
  },
  { deep: true }
);

// 在 script setup 中修改
const tableHeight = ref(0)
const tableContainer = ref(null)
let resizeObserver = null

// 计算表格高度
const calculateTableHeight = () => {
  if (tableContainer.value) {
    // 获取容器的实际可用高度
    const containerHeight = tableContainer.value.clientHeight
    // 获取搜索区域的高度（如果存在）
    const searchCard = document.querySelector('.search-card')
    const searchHeight = searchCard ? searchCard.offsetHeight + 12 : 0 // 12px是gap值

    // 设置表格高度
    // 预留出分页器的高度(40px)和其他边距(12px)
    tableHeight.value = containerHeight - searchHeight
  }
}

// 初始化 ResizeObserver
const initResizeObserver = () => {
  if (tableContainer.value) {
    resizeObserver = new ResizeObserver(() => {
      calculateTableHeight()
    })
    resizeObserver.observe(tableContainer.value)
  }
}

onMounted(() => {
  // 初始计算
  nextTick(() => {
    calculateTableHeight()
    initResizeObserver()
    fetchData() // 初始加载数据
  })
})

onBeforeUnmount(() => {
  // 清理 ResizeObserver
  if (resizeObserver) {
    resizeObserver.disconnect()
    resizeObserver = null
  }
})

// 监听搜索区域的展开/收起状态
watch(showSearchArea, () => {
  // 当搜索区域状态改变时，重新计算表格高度
  nextTick(() => {
    setTimeout(calculateTableHeight, 300) // 等待过渡动画完成
  })
})

// 处理启用状态切换
const handleSwitchChange = async (row, value) => {
  // 构建更新数据
  const updateData = {
    [props.config.primaryKey]: row[props.config.primaryKey],
    [props.config.switchKey]: value
  }

  // 发送请求更新状态
  await request.put(
    `${props.config.apiPrefix}/${row[props.config.primaryKey]}/${props.config.switchKey}`,
    updateData
  )

  // 更新成功提示
  message.success('更新成功')

  // 如果配置了自定义的 onSwitchChange 回调，则调用它
  if (props.config.onSwitchChange) {
    props.config.onSwitchChange(row, value)
  }

  // 触发自定义事件
  emit('switch-change', row, value)

  // 刷新数据
  await fetchData()
}

// 处理批量操作
const handleBatchAction = async (action) => {
  try {
    await dialog.warning({
      title: '确认操作',
      content: `是否确认${BATCH_ACTIONS.find(a => a.action === action).label}？`,
      positiveText: '确定',
      negativeText: '取消'
    })

    loading.value = true
    await request.post(`${props.config.apiPrefix}/batch/${action}`, {
      ids: checkedRowKeys.value
    })
    message.success('操作成功')
    fetchData()
  } finally {
    loading.value = false
  }
}

// 处理刷新
const handleRefresh = () => {
  fetchData()
}

// 处理全屏
const toggleFullscreen = () => {
  const container = document.querySelector('.crud-container')
  if (!isFullscreen.value) {
    container.requestFullscreen()
  } else {
    document.exitFullscreen()
  }
  isFullscreen.value = !isFullscreen.value
}

// 监听全屏变化
onMounted(() => {
  document.addEventListener('fullscreenchange', () => {
    isFullscreen.value = !!document.fullscreenElement
  })
})

onBeforeUnmount(() => {
  document.removeEventListener('fullscreenchange', () => { })
})

// 使用 debounce 创建防抖搜索函数
const debouncedSearch = debounce(() => {
  handleSearch()
}, 300)

// 监听搜索表单的变化
watch(
  () => searchForm,
  () => {
    debouncedSearch()
  },
  { deep: true }
)

// 监听表格大小变化
watch(tableSize, (newSize) => {
  // 触发表格重新渲染
  nextTick(() => {
    calculateTableHeight()
  })
})

// 获取实际的表单字段
const getFormFields = (isChild = false) => {
  if (isChild && props.config.childConfig?.formFields) {
    return props.config.childConfig.formFields
  }
  return props.config.formFields
}

// 修改 handleAddChild 方法
defineExpose(
  {
    fetchData,
    tableData,
    handleAdd,
    handleAddChild: (row, extraData = {}) => {
      isEdit.value = false
      showModal.value = true

      // 使用子项表单字段
      formFields.value = getFormFields(true)

      formData.value = {
        ...extraData,
        [props.config.childConfig?.parentField || 'parent_id']: row[props.config.primaryKey]
      }
    }
  })

// 修改表单渲染
const formFields = ref([])

// 监听表单显示状态
watch(showModal, (val) => {
  if (val) {
    // 根据是否有 parent_id 判断是否为子项
    const isChild = !!formData.value[props.config.childConfig?.parentField || 'parent_id']
    formFields.value = getFormFields(isChild)
  }
})

// 在renderFormItem方法中添加cascader类型支持
const renderFormItem = ({ type, ...props }) => {
  switch (type) {
    // ... other cases ...
    
    case 'cascader':
      return h(NCascader, {
        value: formData.value[props.key],
        options: typeof props.options === 'function' ? columnOptions.value.filter(option => props.options(option)) : props.options,
        clearable: props.clearable,
        filterable: props.filterable,
        placeholder: props.placeholder,
        disabled: props.disabled,
        'onUpdate:value': (value) => {
          formData.value[props.key] = value
          if (props.onUpdateValue) {
            props.onUpdateValue(value)
          }
        },
        style: {
          width: '100%'
        },
        ...props
      })

    case 'tree-select':
      return h(NTreeSelect, {
        value: formData.value[props.key],
        options: props.options,
        clearable: props.clearable,
        filterable: props.filterable,
        placeholder: props.placeholder,
        defaultExpandAll: props.defaultExpandAll,
        checkStrategy: props.checkStrategy,
        keyField: props.keyField,
        labelField: props.labelField,
        childrenField: props.childrenField,
        remote: props.remote,
        cascade: props.cascade,
        multiple: props.multiple,
        virtualScroll: props.virtualScroll,
        maxHeight: props.maxHeight,
        'onUpdate:value': (value) => {
          formData.value[props.key] = value
        },
        style: {
          width: '100%'
        }
      })

    // ... other cases ...
  }
}

// 在watch中处理cascader的options
watch(
  () => props.config.formFields,
  async (fields) => {
    if (!fields) return
    
    for (const field of fields) {
      if (field.type === 'cascader' && typeof field.options === 'function') {
        try {
          columnOptions.value = await field.options()
        } catch (error) {
          console.error('Failed to fetch cascader options:', error)
          columnOptions.value = []
        }
      }
    }
  },
  { immediate: true }
)

// 添加排序相关的状态
const showSortModal = ref(false)
const sortTreeData = ref([])

// 构建排序树形数据
const buildSortTreeData = (data) => {
  // 构建id到节点的映射
  const idMap = new Map()
  data.forEach(item => {
    idMap.set(item.id, {
      key: item.id,
      label: item.name,
      children: []
    })
  })
  
  // 构建树形结构
  const result = []
  data.forEach(item => {
    const node = idMap.get(item.id)
    if (!item.parent_id) {
      result.push(node)
    } else if (idMap.has(item.parent_id)) {
      const parent = idMap.get(item.parent_id)
      parent.children.push(node)
    }
  })

  return result
}

// 处理排序按钮点击
const handleSort = () => {
  sortTreeData.value = buildSortTreeData(tableData.value)
  showSortModal.value = true
}

// 处理排序确认
const handleSortConfirm = async (keys) => {
  try {
    // 发送排序请求
    await request.post(`${props.config.apiPrefix}/sort`, {
      ids: keys
    })
    message.success('排序成功')
    fetchData()
  } catch (error) {
    console.error('Sort failed:', error)
    message.error('排序失败')
  } finally {
    showSortModal.value = false
  }
}

// 分页处理方法
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 判断是否为Vue组件
const isVueComponent = (render, row) => {
  if (typeof render !== 'function') return false
  try {
    const result = render(row)
    return result && typeof result === 'object' && ('__v_isVNode' in result || result.component)
  } catch (e) {
    console.error('Check component error:', e)
    return false
  }
}

// 修改渲染自定义列的方法
const renderCustomColumn = (render, row) => {
  if (typeof render === 'function') {
    try {
      const result = render(row)
      // 如果是Vue组件，直接返回
      if (result && typeof result === 'object' && ('__v_isVNode' in result || result.component)) {
        return result
      }
      // 如果是普通对象，尝试转换为字符串
      if (result && typeof result === 'object') {
        return result.toString?.() || JSON.stringify(result)
      }
      // 返回原始值
      return result
    } catch (e) {
      console.error('Render error:', e)
      return ''
    }
  }
  return render
}

// 修改日期时间格式化函数
const formatDateTime = (value) => {
  if (!value) return ''
  try {
    if (typeof value === 'string') {
      const date = new Date(value.replace(/-/g, '/'))
      return new Intl.DateTimeFormat('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).format(date)
    }
    return value
  } catch (e) {
    console.error('Date format error:', e)
    return value
  }
}
</script>

<style lang="scss" scoped>
.card-label {
  color: var(--primary-color);
}

.crud-container {
  height: 100%;
  display: flex;
  padding: 15px;
  box-sizing: border-box;
  flex-direction: column;

  .crud-header {
    margin-bottom: 16px;
  }

  .crud-content {
    flex: 1;
    height: 100%;
    overflow: hidden;

    .n-data-table {
      height: 100%;
    }
  }
}

.table-card {
  flex: 1;
  margin-top: 10px;
  background: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  :deep(.n-card__content) {
    padding: 16px;
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: auto;
  position: relative;

  .el-table {
    flex: 1;
    overflow: auto;
  }
}

.search-card {
  background: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  flex-shrink: 0;
}

.search-card :deep(.n-card-header),
.table-card :deep(.n-card-header) {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.search-card :deep(.n-card__content) {
  padding: 16px;
}

.search-header {
  display: flex;
  font-weight: bold;
  color: black;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
}

.search-header :deep(.n-button) {
  border: none !important;
  padding: 0;
  margin: 0;
  height: auto;
  line-height: 1;
}

.search-header :deep(.n-button:hover),
.search-header :deep(.n-button:focus),
.search-header :deep(.n-button:active) {
  background-color: transparent !important;
  box-shadow: none !important;
  outline: none !important;
}

.search-header :deep(.n-button:not(.n-button--disabled):focus) {
  box-shadow: none !important;
}

.search-content {
  transition: all 0.3s ease;
  max-height: 500px;
  overflow: hidden;
}

.search-content :deep(.n-form-item) {
  margin-bottom: 8px;
}

.search-content :deep(.n-form-item-label) {
  font-size: 13px;
  padding-right: 8px;
  height: 28px;
  line-height: 28px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.search-content :deep(.n-form-item-blank) {
  min-height: 28px;
}

.search-content :deep(.n-form-item-feedback-wrapper) {
  min-height: 0 !important;
  margin-top: 0 !important;
  padding-top: 0 !important;
}

.search-content :deep(.n-input),
.search-content :deep(.n-select),
.search-content :deep(.n-date-picker) {
  height: 28px;
}

.search-content-collapsed {
  max-height: 0;
  padding: 0;
  margin: 0;
}

.search-actions {
  margin-top: 12px;
  padding-top: 12px;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  border-top: 1px solid #f0f0f0;
}

.search-actions :deep(.n-button) {
  padding: 0 16px;
  height: 32px;
  font-size: 13px;
}

.toolbar-card {
  margin-bottom: 12px;

  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.custom-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 12px;
  transition: all 0.3s;

  .n-icon {
    font-size: 16px;
  }

  span,
  .button-label {
    color: inherit;
    transition: color 0.3s;
  }

  &:not(.n-button--primary-type) {
    &:hover {
      color: var(--primary-color);
      background-color: var(--primary-bg);

      span,
      .button-label {
        color: var(--primary-color);
      }
    }
  }

  &.n-button--primary-type {
    background-color: var(--primary-color);
    border-color: var(--primary-color);

    &:hover {
      background-color: var(--primary-hover);
      border-color: var(--primary-hover);
    }

    &:active {
      background-color: var(--primary-active);
      border-color: var(--primary-active);
    }

    span,
    .button-label {
      color: #fff;
    }
  }

  &.n-button--error-type {
    &:hover {
      color: #fff;
      background-color: var(--error-color);
      border-color: var(--error-color);

      span,
      .button-label {
        color: #fff;
      }
    }
  }
}

// 表格操作列按钮样式
.n-data-table {
  :deep(.n-button) {
    padding: 4px 12px;
    background-color: transparent !important; // 确保背景色透明

    &.n-button--quaternary {
      &:hover {
        color: var(--primary-color);
        background-color: var(--primary-bg) !important;
      }
    }

    &.n-button--error-type {
      &:hover {
        color: var(--error-color);
        background-color: var(--error-hover-color) !important;
      }
    }
  }
}

// 工具栏按钮样式
.toolbar {
  .n-button {
    &.n-button--quaternary {
      &:hover {
        color: var(--primary-color);
        background-color: var(--primary-bg);
      }
    }
  }
}

// 搜索区域按钮样式
.search-actions {
  .n-button {
    &:not(.n-button--primary-type) {
      &:hover {
        color: var(--primary-color);
        border-color: var(--primary-color);
      }
    }
  }
}

:deep(.n-cascader) {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right {
  display: flex;
  gap: 8px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

// 添加 element-plus 的样式变量
:root {
  --el-color-primary: var(--primary-color);
  --el-color-primary-light-3: var(--primary-hover);
  --el-color-primary-dark-2: var(--primary-active);
  --el-color-error: var(--error-color);
}

/* 添加表格相关样式 */
.table-container {
  :deep(.el-table) {
    /* 表头样式 */
    th {
      text-align: left;  // 表头默认居左
      padding-left: 16px !important;
      
      &.is-center {  // 序号列等需要居中的表头
        text-align: center;
        padding-left: 0 !important;
      }
    }
    
    /* 单元格样式 */
    td {
      text-align: left;  // 单元格默认居左
      padding-left: 16px !important;
      
      &.el-table-column--center {  // 序号列等需要居中的单元格
        text-align: center;
        padding-left: 0 !important;
      }
    }

    /* 操作列居中 */
    .action-buttons {
      text-align: center;
      padding-left: 0 !important;
    }
  }
}

/* 确保按钮内容居中 */
:deep(.el-button) {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

/* 确保图标和文字对齐 */
:deep(.el-icon) {
  margin-right: 4px;
  display: inline-flex;
  align-items: center;
}

/* 自定义表格样式 */
.custom-table {
  // 表头样式
  :deep(.el-table__header) {
    th {
      background-color: #f7f8fa !important;
      color: #0f172a;
      font-weight: 500;
      border: none;
      height: 46px;
      font-size: 14px;
      transition: all 0.2s ease;
      
      &.is-leaf {
        border-bottom: 1px solid #e2e8f0;
      }

      // 表头悬停效果
      &:hover {
        background-color: #eff1f5 !important;
        color: #0284c7;
      }
    }
  }

  // 表格主体样式
  :deep(.el-table__body) {
    td {
      padding: 14px 16px;  // 修改内边距，保持左对齐的间距
      color: #334155;
      font-size: 14px;
      border-bottom: 1px solid #f1f5f9;
      transition: all 0.2s ease;
      background-color: #ffffff;

      // 序号列和操作列保持居中
      &.el-table-column--center {
        padding: 14px 0;
      }
    }
  }

  // 行悬停效果
  :deep(.el-table__row) {
    &:hover {
      td {
        background-color: #fafafa !important;
        color: #0f172a;
      }
    }
  }

  // 斑马纹样式
  :deep(.el-table__row--striped) {
    td {
      background-color: #f8fafc;
    }
  }

  // 树形表格展开图标
  :deep(.el-table__expand-icon) {
    color: #64748b;
    transition: all 0.2s ease;
    width: 26px;
    height: 26px;
    line-height: 26px;
    text-align: center;
    border-radius: 6px;
    
    &:hover {
      background-color: #f1f5f9;
      color: #0284c7;
    }
    
    &.el-table__expand-icon--expanded {
      transform: rotate(90deg);
      color: #0284c7;
      background-color: #f0f9ff;
    }
  }

  // 表格边框和圆角
  :deep(.el-table) {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    
    &::before {
      display: none;
    }
  }

  // 分页器样式
  .pagination-container {
    margin-top: 20px;
    padding: 16px 0;
    border-top: 1px solid #f1f5f9;
    
    :deep(.el-pagination) {
      .el-pagination__total,
      .el-pagination__sizes {
        color: #64748b;
        font-size: 13px;
      }
      
      .el-pager li {
        background: transparent;
        color: #64748b;
        border-radius: 6px;
        transition: all 0.2s ease;
        
        &:hover {
          color: #0284c7;
          background-color: #f0f9ff;
        }
        
        &.is-active {
          color: #fff;
          background-color: #0284c7;
          font-weight: 500;
        }
      }
      
      .btn-prev,
      .btn-next {
        border-radius: 6px;
        transition: all 0.2s ease;
        
        &:hover:not(:disabled) {
          color: #0284c7;
          background-color: #f0f9ff;
        }
        
        &:disabled {
          color: #cbd5e1;
        }
      }
    }
  }
}

// 分页器样式优化
.pagination-container {
  margin-top: 20px;
  padding: 10px 0;
  display: flex;
  justify-content: flex-end;
  
  :deep(.el-pagination) {
    padding: 0;
    margin: 0;
    font-weight: normal;
    
    .el-pagination__total,
    .el-pagination__sizes {
      margin-right: 16px;
    }
    
    .el-pagination__jump {
      margin-left: 16px;
    }
    
    button {
      background: transparent;
      
      &:hover {
        color: var(--el-color-primary);
      }
    }
  }
}
</style>
